<template>
    <div class="app">
        <div class="nav">
            <Navict/>
        </div>
        <div class="head">
            <div class="head-l">
                <div class="shadow"><p class="head-txt"><span style="margin-right: 60px;">你可以做些什么</span></p></div>
            </div>
            <div class="head-r">
            </div>
        </div>
        <div class="title-r"><div class="title-d"><p style="margin-left: 50px;">宠物领养</p></div></div>
        <div class="mid">
            <div class="mid-txt">宠物类型</div>
            <div class="select">
                <!-- element-plus的radio组件，可以快速实现选择框 -->
                <!-- 可以查看官方文档 -->
                <el-radio-group  v-model="radio1" size="large" fill="#03a850">
                    <el-radio-button label="宠物狗" />
                    <el-radio-button label="宠物猫" />
                    <el-radio-button label="其它宠物" />
                    <el-radio-button label="全部宠物" />
                </el-radio-group>
            </div>
        </div>
        <div class="rescure">
            <!-- 使用分页后的图片进行展示，然后再次进行切割达到一行几个的需求 -->
            <div class="pet-img-list" v-for="(item,index) in sliceList(myStore.dataList,5)"  :key="index">
                <div class="pet-info" v-for="(items,i) in item" :key="i">
                    <div class="pet-c">
                        <img :src='items.img' class="pet-img" alt="Image">
                        <!-- 这里是鼠标悬停后显示的信息，可以点击跳转到详情 -->
                        <div class="gray" @click="toinfo(items.pet_id)"><p class="c-txt">➨</p></div>
                        
                    </div>
                    <div class="pet-desc">
                        <div class="pet-name-txt">
                            <p style="font-size: 10px;color:#03a850;line-height: 10px;">{{ items.type }}</p>
                            <p style="margin-top: 5px;margin-bottom: 5px;">{{ items.name }}</p>
                            <div style="color: red;font-size: 15px;" v-if="items.appointment === '已被预约'">已被预约</div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- <div style="height: 50px;margin-left: 10px;margin-bottom: 20px; background-color: #edf3d1;margin-top: 20px;width: 200px;">
                element-plus的分页组件，可以快速实现分页功能 
                <el-pagination 
                    background 
                    layout="prev, pager, next, jumper"
                    :current-page="currentPage"  
                    :page-size="pageSize"  
                    :total="totalItems"  
                    @current-change="handlePageChange"  
                    ></el-pagination>
            </div> -->
        </div>
        <div class="title-r"><div class="title-d"><p style="margin-left: 50px;">宠物救助</p></div></div>
        <div class="rescue-in">
            <div class="up-r">
                <div class="res-l">
                    <div class="form_">
                        <!-- element-plus的表单组件，可以快速实现表单功能  -->
                        <el-form :model="pets"  class="form-l">
                            <el-form-item label="宠物姓名">
                                <div style="width: 400px;">
                                    <el-input v-model="pets.name" placeholder="" />
                                </div>
                            </el-form-item>
                            <el-form-item label="宠物种类" >
                                <el-select style="width: 400px;" v-model="pets.desc" placeholder="">
                                    <el-option label="猫" value="猫" />
                                    <el-option label="狗" value="狗" />
                                    <el-option label="其它" value="其它" />
                                </el-select>
                            </el-form-item>
                            <el-form-item label="宠物年龄">
                                <el-input style="width: 400px;" v-model="pets.age" />
                            </el-form-item>
                            <el-form-item label="宠物品种">
                                <div style="width: 400px;">
                                    <el-input v-model="pets.type" placeholder="" />
                                </div>
                            </el-form-item>
                            <el-form-item label="宠物性别">
                            <el-radio-group v-model="pets.gender">
                                <el-radio label="公" />
                                <el-radio label="母" />
                            </el-radio-group>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
                <div class="res-r">
                    <div class="res-r-img">
                        <!-- element-plus的上传图片组件，可以拖拽或者点击上传图片 -->
                        <el-upload 
                            drag
                            action="http://localhost:8000/pet/insert"
                            :disabled="pets.name !== '' ? false : true"
                            :data="pets"
                            :on-success="handleSuccess"
                            :before-upload="beforeUpload"
                            multiple
                        >
                            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                            <div class="el-upload__text">
                                拖动到此 <em>或者点我上传</em>
                            </div>
                            <template #tip>
                                <div class="el-upload__tip" style="margin-left: 10px;background-color: #fff;">
                                    jpg/png 文件的大小不能超过500kb
                                </div>
                            </template>
                        </el-upload>
                    </div>
                </div>
            </div>
        </div>
        <div class="nav-b"><Bottom/></div>
    </div>
</template>

<script  setup>
import { ref,watch,onMounted } from 'vue'
import Navict from './Navict.vue'
import { reactive } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'
import Bottom from './ButtomNavict.vue'
import { useRouter } from 'vue-router'; 
import { ElMessage, ElPagination } from 'element-plus'; 
import axios from 'axios'   
import { useStore } from '../stores/counter'

const myStore = useStore()

function base64ToBlobUrl(base64String, mimeType = "application/octet-stream") {
  // 将 Base64 字符串解码为二进制数据
  const binaryData = Uint8Array.from(atob(base64String), c => c.charCodeAt(0));

  // 创建 Blob 对象
  const blob = new Blob([binaryData], { type: mimeType });

  // 通过 URL.createObjectURL 创建 Blob 的 URL
  const blobUrl = URL.createObjectURL(blob);

  return blobUrl;
}

function convertBase64ToBlobUrls(arrayOfObjects) {
  return arrayOfObjects.map(obj => {
    // 检查对象是否包含 img 字段
    if (obj && obj.img) {
      // 将 Base64 字符串转换为 Blob URL
      const blobUrl = base64ToBlobUrl(obj.img);
      
      // 返回新对象，img 字段替换为 Blob URL
      return { ...obj, img: blobUrl };
    } else {
      // 对于没有 img 字段的对象，保持不变
      return obj;
    }
  });
}


// 定义触发操作的方法，在组件挂载后执行
const fetchData = async (url) => {
  try {
    // 发起请求
    const response = await axios.get(url)

    // 更新数据到 Pinia Store
    myStore.updateDataList(convertBase64ToBlobUrls(response.data.result))
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}

// 在组件挂载后执行 fetchData 方法
onMounted(() => {
  fetchData('http://localhost:8000/pet/pets')
})


const router = useRouter();


//定义一个ref对象radio1，用于存储宠物的种类
const radio1 = ref('全部宠物')



//定义一个reactive对象pets，用于存储宠物的信息
let pets = reactive({
  name: '',  //宠物的名字
  desc: '',  //宠物的描述
  age: '',  //宠物的年龄
  type: '', //宠物的类型
  gender: '',  //宠物的性别
})

function handleSuccess(response, file, fileList){
    // 上传成功后执行的操作
    ElMessage({
        message:"上传成功",
        type:"success"
    })
    location.reload();
    
}




const beforeUpload = async (file) => {
      // 在这里可以进行一些上传前的逻辑
    const storedData = sessionStorage.getItem('token');
    const t = JSON.parse(storedData)
    if(t === null){
        ElMessage({
            message:"你未登录，请登录",
            type:"error"
        })
        return false
    }else{
        return true;
    }
     
};

//将数组切割成指定数量的数组
function sliceList(list,count){
  let arr = []
  //使用循环切割
  for(let i = 0;i<list.length;i++){
    if(i%count === 0){
      //如果i是count的倍数，就将数组添加到arr中
      arr.push([])
    }
    arr[arr.length-1].push(list[i])
  }
  return arr
}


//这里还需要根据选择的数据发送请求，是不同的四个请求
watch(radio1,(newVal,oldVal) => {
    if(newVal === "宠物狗"){
        fetchData('http://localhost:8000/pet/dogs')
    }else if(newVal === "宠物猫"){
        fetchData('http://localhost:8000/pet/cats')
    }else if(newVal === "其它宠物"){
        fetchData('http://localhost:8000/pet/others')
    }else{
        fetchData('http://localhost:8000/pet/pets')
    }
})

//使用路由传参跳转，为什么要传参？
//因为每次点击的图片不一样，所以要传参
function toinfo(pet_id){
    router.push({path:'/info',query:{id:pet_id}})
}

</script>



<style scoped>
    .app{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
    }
    .nav-b{
        width: 100%;
        margin-top: 20px;
    }
    .head{
        width: 100%;
        display: flex;
        justify-content: space-between;
    }
    .head-l{
        position: relative;
        width: 50%;
        z-index: 1;
        height: 300px;
        background-image: url(../static/login/bg1.png);
        background-size: 100% 100%;
    }
    .shadow{
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 2;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        backdrop-filter: blur(10px);
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
    .head-txt{
        width: 60%;
        height: 80px;
        color: #03a850;
        background-color: #edf3d1;
        font-size: 30px;
        text-align: right;
        line-height: 80px;
        border-radius: 5px;
    }
    .head-r{
        width: 50%;
        height: 300px;
        background-image: url(../static/login/bg1.png);
        background-size: 100% 100%;
    }
    .up-r{
        width: 100%;
        display: flex;
        justify-content: space-evenly;
    }
    .res-l{
        width: 50%;
        margin-top:1%;
    }
    .res-r{
        width: 40%;
        background-color: #fff;
        margin-top: 10px;
        margin-right: 20px;
        border-radius: 8px;
        margin-bottom: 10px;
    }
    .res-r-img{
        width: 100%;
        height: 300px;
    }
    .form-l{
        width: 100%;
        margin: 10px;
        padding: auto;
    }
    .rescue-in{
        width: 98%;
        background-color: #edf3d1;
        margin:0 auto;
        margin-top:  20px;
    }
    .title-r{
        width: 98%;
        height: 80px;
        color: white;
        font-size: 30px;
        line-height: 110px;
        margin:0 auto;
        margin-top: 20px;
        background-color: #edf3d1;
        overflow: hidden;
    }
    .title-d{
        width: 200px;
        background-color: #03a850;
        border-radius: 38px;
        margin-left: -40px;
    }
    .rescure{
        width: 98%;
        background-color: #edf3d1;
        margin:0 auto;
        margin-top:  20px;
    }
    .pet-desc{
        width: 100%;
        height: 100px;
        background-color: #fff9ed;
        display: flex;
        flex-direction: column;
        justify-content: center;
        border-bottom-left-radius: 8px;
        border-bottom-right-radius: 8px;
    }
    .pet-name-txt{
        color: black;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
        line-height: 20px;

    }
    .pet-info{
        width: 268px;
        height: 400px;
        margin:10px;
    }
    .pet-c{
        position: relative;
        width: 100%;
        height: 300px;
        z-index:1;
        overflow: hidden;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
    }
    .pet-c:hover .gray{
        display: block;
        cursor: pointer;
    }
    .pet-c:hover .pet-img{
        transform: scale(1.4);
        transition: all 0.5s;
    }
    .gray{
        display: none;
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 2;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
        color: white;
        backdrop-filter: blur(10px);
        text-align: center;
        line-height: 300px;
        font-size: 40px;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
    }
    .gray :hover{
        cursor: pointer;
    }
    .pet-img{
        width: 100%;
        height: 100%;
        position: relative;
        z-index: 1;
        border-top-left-radius: 8px;
        border-top-right-radius: 8px;
    }
    .pet-img-list{
        width: 100%;
        display: flex;
        justify-content: start;
    }

    .mid{
        width: 98%;
        height: 100px;
        margin:0 auto;
        margin-top: 20px;
        background-color: #edf3d1;
        border-radius: 0px;
        padding: 10px;
        display: flex;
        justify-content: space-between
    }
    .mid-txt{
        color: black;
        width: 80px;
        height: 100%;
        font-weight: bold;
        margin-left: 20px;
        margin-top: 25px;
    }
    .select{
        width: 98%;
        /* margin-left: 20px; */
        margin-top: 16px;
    }
    .nav{
        width: 100%;
        height: 200px;
        margin-bottom: 10px;
    }
    ::v-deep .el-radio-button :hover{
        color: #03a850;
        
    }
    ::v-deep .el-radio-button {
        /* width: 120px; */
        border: #03a850 1px solid;
        border-radius: 2px;
        margin-left: 20px;
        background-color: #edf3d1;
    }
    :deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
         background-color: #03a850 !important;
    }
</style>